package com.jsmy.marketing.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.jsmy.marketing.R;
import com.jsmy.marketing.adapter.ComFragmentAdapter;
import com.jsmy.marketing.api.RetrofitManager;
import com.jsmy.marketing.base.BaseActivity;
import com.jsmy.marketing.bean.VersionBean;
import com.jsmy.marketing.common.Link;
import com.jsmy.marketing.fg.BaseFragment;
import com.jsmy.marketing.fg.BusinessFragment;
import com.jsmy.marketing.fg.DataFragment;
import com.jsmy.marketing.fg.HomeFragment;
import com.jsmy.marketing.fg.StudentFragment;
import com.jsmy.marketing.fg.TestFragment;
import com.jsmy.marketing.manager.UserManager;
import com.jsmy.marketing.utils.ActivityManager;
import com.jsmy.marketing.utils.DialogUtils;
import com.jsmy.marketing.utils.GlideApp;
import com.jsmy.marketing.utils.ToastUtil;
import com.jsmy.marketing.utils.VersionUtil;
import com.jsmy.marketing.view.GlideCircleTransform;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页
 */
public class MainActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.navigation)
    BottomNavigationView navigation;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;

    @BindView(R.id.right)
    CoordinatorLayout right;
    @BindView(R.id.nav_view)
    NavigationView left;
    @BindView(R.id.mviewpager)
    ViewPager mViewPager;
    @BindView(R.id.img_avatar)
    ImageView imgAvatar;
    @BindView(R.id.tv_content)
    TextView tvContent;
  @BindView(R.id.img_fresh)
  ImageView mIvTitleRight;
    private boolean isDrawer = false;



    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mViewPager.setCurrentItem(0);
                    return true;
                case R.id.navigation_student:
                    mViewPager.setCurrentItem(1);
                    return true;
                case R.id.navigation_dashboard:
                    mViewPager.setCurrentItem(2);
                    return true;
                case R.id.navigation_notifications:
                    mViewPager.setCurrentItem(3);
                    return true;
            }
            return false;
        }
    };

    private ComFragmentAdapter mFragmentAdapter;
    BaseFragment currentFragment;
    HomeFragment homeFragment=new HomeFragment();
    StudentFragment studentFragment=new StudentFragment();
    DataFragment dataFragment=new DataFragment();
    BusinessFragment businessFragment=new BusinessFragment();
    @Override
    protected int resId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        GlideApp.with(this).load(UserManager.getInstance().getIco()).circleCrop().transform(new GlideCircleTransform()).into(imgAvatar);
        tvContent.setText(UserManager.getInstance().getTitle());
        GlideApp.with(this).load(UserManager.getInstance().getIco()).circleCrop() .transform(new GlideCircleTransform()).into((ImageView) left.getHeaderView(0).findViewById(R.id.img_avatar));
        ((TextView) left.getHeaderView(0).findViewById(R.id.tv_name)).setText("金牌：" +UserManager.getInstance().getUsername());
        ((TextView) left.getHeaderView(0).findViewById(R.id.tv_content)).setText( UserManager.getInstance().getTitle());

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        left.getMenu().getItem(0).setTitle(UserManager.getInstance().getDkzt());

        left.setNavigationItemSelectedListener(this);
        left.getHeaderView(0).findViewById(R.id.img_avatar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                       if (drawer.isDrawerOpen(GravityCompat.START)){
                           drawer.closeDrawer(GravityCompat.START);
                       }else {
                           drawer.openDrawer(GravityCompat.START);
                       }
                       openActivity(UserActivity.class);
            }
        });
        right.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (isDrawer) {
                    return left.dispatchTouchEvent(motionEvent);
                } else {
                    return false;
                }
            }
        });
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                isDrawer = true;
                //获取屏幕的宽高
                WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                Display display = manager.getDefaultDisplay();
                //设置右面的布局位置  根据左面菜单的right作为右面布局的left   左面的right+屏幕的宽度（或者right的宽度这里是相等的）为右面布局的right
                right.layout(left.getRight(), 0, left.getRight() + display.getWidth(), display.getHeight());
            }

            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {
                isDrawer = false;
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        mFragmentAdapter=new ComFragmentAdapter(getSupportFragmentManager(),4) {
            @Override
            public Fragment getItem(int postion) {
              currentFragment =new TestFragment();
                switch (postion){
                    case 0:
                        if (homeFragment==null){
                            homeFragment=new HomeFragment();
                        }
                        currentFragment =homeFragment;
                        break;
                    case 1:
                        if (studentFragment==null){
                            studentFragment=new StudentFragment();
                        }
                        currentFragment =studentFragment;
                        break;
                    case 2:
                        if (dataFragment==null){

                            dataFragment=new DataFragment();
                        }
                        currentFragment =dataFragment;
                        break;
                    case 3:
                        if (businessFragment==null){
                            businessFragment=new BusinessFragment();
                        }
                        currentFragment =businessFragment;
                        break;
                }
                return currentFragment;
            }
        };
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setAdapter(mFragmentAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        mIvTitleRight.setImageResource(R.drawable.ic_menu_fresh);
                        navigation.setSelectedItemId(R.id.navigation_home);
                        break;
                    case 1:
                        mIvTitleRight.setImageResource(R.drawable.add_user);
                        navigation.setSelectedItemId(R.id.navigation_student);
                        break;
                    case 2:
                        mIvTitleRight.setImageResource(R.drawable.ic_menu_fresh);
                        navigation.setSelectedItemId(R.id.navigation_dashboard);
                        break;
                    case 3:
                        mIvTitleRight.setImageResource(R.drawable.ic_menu_fresh);
                        navigation.setSelectedItemId(R.id.navigation_notifications);
                        break;
                }
                super.onPageSelected(position);
            }
        });
        requestVersionInfo();
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    //    版本信息
    private void requestVersionInfo() {
        Map<String,Object> map = new HashMap<>();
        map.put("type","android");
        map.put("versioncode", VersionUtil.getVersionName(getApplicationContext()));
        mPresenter.loadData(RetrofitManager.getInstance().getVersionInfo(map), Link.APP_VERSION_INFO);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_sign) {
//            presenter.saveqdinfo();
            return true;
        } else if (id == R.id.nav_card) {
//            ARouter.getInstance().build(AR.A_SHARE)
//                    .withString("id", "")
//                    .withString("url", API.APP_CARD)
//                    .withString("title", "电子名片")
//                    .withString("note", "")
//                    .withString("share", "N")
//                    .navigation();
            Bundle b = new Bundle();
            b.putString("title","电子名片");
            openActivity(WebActivity.class,b);
            return true;
        } else if (id == R.id.nav_business) {
//            ARouter.getInstance().build(AR.A_SHARE)
//                    .withString("id", "")
//                    .withString("url", API.APP_BUSI)
//                    .withString("title", "业务统计")
//                    .withString("note", "")
//                    .withString("share", "N")
//                    .navigation();mViewPager
            Bundle b = new Bundle();
            b.putString("title","业务统计");
            openActivity(WebActivity.class,b);
            return true;
        } else if (id == R.id.nav_about) {
//            ARouter.getInstance().build(AR.A_SHARE)
//                    .withString("id", "")
//                    .withString("url", API.APP_ABOUT)
//                    .withString("title", "关于我们")
//                    .withString("note", "")
//                    .withString("share", "N")
//                    .navigation();
            Bundle b = new Bundle();
            b.putString("title","关于我们");
            openActivity(WebActivity.class,b);
            return true;
        } else if (id == R.id.nav_update) {
            if (VersionUtil.getVersionName(this).equals(bean.getNew_version())) {
                ToastUtil.showShort(this, "当前已是最新版本！");
            } else {
                DialogUtils.showVersionDialog(this, bean.getNew_version(), bean.getUpdate_log(), bean.getApk_file_url());
            }
            return true;
        } else if (id == R.id.nav_setting) {
//            ARouter.getInstance().build(AR.A_SETTING).navigation();
            openActivity(SettingActivity.class);
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @OnClick({R.id.img_avatar, R.id.img_fresh})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.img_avatar:
                if (drawer.isDrawerOpen(GravityCompat.START)){
                    drawer.closeDrawer(GravityCompat.START);
                }else {
                    drawer.openDrawer(GravityCompat.START);
                }
                break;
            case R.id.img_fresh:
//                presenter.getbasicinfo();
                switch (navigation.getSelectedItemId()) {
                    case R.id.navigation_home:
//                        ((BaseFragment)mFragmentAdapter.getItem(mViewPager.getCurrentItem())).update();
                        homeFragment.update();
                        break;
                    case R.id.navigation_student:
//                        ((StudentFragment)fragment).update();
//                        ((BaseFragment)mFragmentAdapter.getItem(mViewPager.getCurrentItem())).update();
//                        studentFragment.update();
                          openActivity(AddCustomerActivity.class);
                        break;
                    case R.id.navigation_dashboard:
//                        ((DataFragment) FragmentSmanager.getInstance().getFragment(FragmentSmanager.DATA)).updata();
//                        ((DataFragment)fragment).update();
//                        ((BaseFragment)mFragmentAdapter.getItem(mViewPager.getCurrentItem())).update();
                        dataFragment.update();

                        break;
                    case R.id.navigation_notifications:
//                        ((BusinessFragment) FragmentSmanager.getInstance().getFragment(FragmentSmanager.BUSINESS)).updata();
//                        ((BusinessFragment)fragment).update();
//                        ((BaseFragment)mFragmentAdapter.getItem(mViewPager.getCurrentItem())).update();
                        businessFragment.update();

                        break;
                }
                break;
        }
    }
    VersionBean.DataBean bean;
    @Override
    public void refreshData(Object object, String position) {
        switch (position) {
            case Link.APP_VERSION_INFO:
                bean = ((VersionBean) object).getData();
                break;
            case Link.APP_BASIC_INFO:
//                info = ((LoginBean) object).getData();
//                tvContent.setText(info.getTitle());
//                left.getMenu().getItem(0).setTitle(info.getDkzt());
                break;
            case Link.APP_SAVE_QD_INFO:
                ToastUtil.showShort(this,"打卡成功！");
//                presenter.getbasicinfo();
                break;
        }
    }

    private static boolean isExit = false;

    // /** 双击返回按钮，退出 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
        }
        return false;
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtil.showShort(this,"再按一次退出程序");
            new Timer().schedule(new TimerTask() {

                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            ActivityManager.getInstance().exit();
        }
    }
}
